import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:amap_map/amap_map.dart';
import 'package:getx_scaffold/common/utils/date_util.dart';
import 'package:oramemo/common/config/map_config.dart';
import 'package:oramemo/common/langs/text_key.dart';
import 'package:oramemo/common/styles/colors.dart';
import 'package:oramemo/entity/device_mine_entity.dart';
import 'package:oramemo/generated/assets.dart';
import 'package:oramemo/pages/facility/facility_home/facility_logic.dart';
import 'package:x_amap_base/x_amap_base.dart';

class PositionFlutterMapView extends StatefulWidget {
  const PositionFlutterMapView({super.key, this.isShowInfo = true});

  final isShowInfo;

  @override
  State<StatefulWidget> createState() => _ShowMapPageState();
}

class _ShowMapPageState extends State<PositionFlutterMapView> {
  static const LatLng mapCenter = LatLng(
    22.520922,
    114.055198,
  );
  static const LatLng markerPosition = LatLng(
    22.520922,
    114.055198,
  );
  static const CameraPosition _kInitialPosition = CameraPosition(
    target: mapCenter,
    zoom: 15.0,
  );
  bool _hasInitMarker = false;
  static const String _startIconPath = Assets.positionMapPosition;
  final String _iconPath = _startIconPath;

  final Map<String, Marker> _initMarkerMap = <String, Marker>{};

  @override
  Widget build(BuildContext context) {
    _initMarker();
    AMapInitializer.init(context, apiKey: MapConfig.amapApiKeys);
    AMapInitializer.updatePrivacyAgree(MapConfig.amapPrivacyStatement);
    final AMapWidget map = AMapWidget(
      initialCameraPosition: _kInitialPosition,
      onMapCreated: onMapCreated,
      markers: Set<Marker>.of(_initMarkerMap.values),
    );

    if (!widget.isShowInfo) {
      return map;
    } else {
      return Stack(
        children: [
          ConstrainedBox(
            constraints: const BoxConstraints.expand(),
            child: SizedBox(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              child: map,
            ),
          ),
          SafeArea(
              child: Container(
                margin: const EdgeInsets.all( 10),
                padding: const EdgeInsets.all( 0),
                decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(50),
                  boxShadow: [BoxShadow(color: Colors.grey.shade400, blurRadius: 3)],),
                child: IconButton(
                    onPressed: () => Get.back(),
                    icon: const Icon(Icons.arrow_back_ios_new,
                        color: Colours.text_gray, size: 24)),
              )),
          Positioned(
            bottom: 10,
            child: GetBuilder<FacilityLogic>(
                init: FacilityLogic(),
                builder: (logic) {
                  return MapInfoWidget(
                    onPressed: () {
                      _mapController.moveCamera(
                          CameraUpdate.newCameraPosition(const CameraPosition(
                        target: markerPosition,
                        zoom: 15.0,
                      )));
                      logic.update();
                    },
                    data: logic.state.data,
                  );
                }),
          )
        ],
      );
    }
  }

  late AMapController _mapController;

  void onMapCreated(AMapController controller) {
    setState(() {
      _mapController = controller;
    });
  }

  void _initMarker() async {
    if (_hasInitMarker) {
      return;
    }
    Marker marker = Marker(
        position: markerPosition,
        icon: BitmapDescriptor.fromIconPath(_iconPath));
    setState(() {
      _hasInitMarker = true;
      _initMarkerMap[marker.id] = marker;
    });
  }
}

class MapInfoWidget extends StatelessWidget {
  const MapInfoWidget({
    super.key,
    required this.onPressed,
    required this.data,
  });

  final DeviceMineData data;
  final Function() onPressed;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: Get.width - 40,
      margin: const EdgeInsets.fromLTRB(20, 20, 20, 20),
      padding: const EdgeInsets.fromLTRB(10, 5, 5, 10),
      decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [BoxShadow(color: Colors.grey.shade300, blurRadius: 3)],
          borderRadius: const BorderRadius.all(Radius.circular(8))),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                data.deviceName ?? '',
                style: const TextStyle(
                    fontSize: 16,
                    color: Colours.text,
                    fontWeight: FontWeight.w600),
              ),
              TextButton(onPressed: onPressed, child: Text(TextKey.refresh.tr)),
            ],
          ),
          Text(
            data.device?.deviceAddress ?? '',
            style: const TextStyle(
                fontSize: 14, color: Colours.text, fontWeight: FontWeight.w500),
          ),
          Text(
            DateUtil.formatDate(DateTime.now()),
            style: const TextStyle(
                fontSize: 14,
                color: Colours.text_gray,
                fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }
}
